import { useState,useEffect } from "react";


function MyComponent2() {


    const [width,setWith] = useState(window.innerWidth)
    const [height,setHeight] = useState(window.innerHeight)

    function handleResize() {
        setWith(window.innerWidth)
        setHeight(window.innerHeight)
    }

    // 侦听窗口变化1
    // 缺点：每次窗口变化都会执行，添加一个事件监听器会影响性能
    // window.addEventListener('resize',handleResize)
    // console.log("WINDOW SIZE CHANGED")


    // 侦听窗口变化2
    useEffect(()=>{
        window.addEventListener('resize',handleResize)
        console.log("EVENT LISTENED")

        // 清理函数,在组件卸载时执行
        return ()=>{
            window.removeEventListener('resize',handleResize)
            console.log("EVENT REMOVED")
        }
    },[])


    // 侦听窗口变化(变量)3
    useEffect(()=>{
        document.title = `width: ${width} height: ${height}`
    },[width,height])

    return (
        <div>
            <p>Window width: {width}px</p>
            <p>Window height: {height}px</p>

        </div>
    )

}

export default MyComponent2